package chans

import (
	"context"
)

type RunOne struct {
	e      *Entity
	fn     func(ctx context.Context)
	cancel context.CancelFunc
}

func NewRunOne(fn func(ctx context.Context)) *RunOne {
	e := &RunOne{e: NewEntity(1)}
	e.e.SetHandler(func(no, num int, data interface{}) {
		fn(data.(context.Context))
	})
	return e
}

func (this *RunOne) Run() {
	ctx, cancel := context.WithCancel(context.Background())
	if this.cancel != nil {
		this.cancel()
	}
	this.cancel = cancel
	this.e.Do(ctx)
}
